﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace Bnbjoy.Tester
{
    public class ServiceManager
    {
        private static ServiceManager manager;
        private static object lockObj = new object();

        private ServiceManager() { }

        public static ServiceManager Instance 
        {
            get 
            {
                if (manager == null) 
                {
                    lock (lockObj) 
                    {
                        if (manager == null) 
                        {
                            manager = new ServiceManager();
                        }
                    }
                }

                return manager; ;
            }
        }

        /// <summary>
        /// Get请求
        /// </summary>
        /// <param name="accessToken"></param>
        /// <param name="subUrl"></param>
        /// <returns></returns>
        public async Task<string> GetService(string accessToken, string subUrl) 
        {
            string url = TokenManager.Instance.ApiUrl.TrimEnd('/') + "/api/";
            url += subUrl;

            var client = new HttpClient();
            client.SetBearerToken(accessToken);
            var result = await client.GetStringAsync(new Uri(url));
            return result;
        }

        /// <summary>
        /// Post请求
        /// </summary>
        /// <param name="accessToken"></param>
        /// <param name="subUrl"></param>
        /// <param name="content"></param>
        /// <returns></returns>
        public async Task<HttpPostResponse> PostService(string accessToken, string subUrl, string jsonParam) 
        {
            string url = TokenManager.Instance.ApiUrl.TrimEnd('/') + "/api/";
            url += subUrl;

            var client = new HttpClient();
            client.SetBearerToken(accessToken);
            var response = await client.PostAsync(new Uri(url), new StringContent(jsonParam, System.Text.Encoding.UTF8, "application/json"));
            var content = await response.Content.ReadAsStringAsync();
            HttpPostResponse responseWrapper = new HttpPostResponse
            {
                StatusCode = response.StatusCode,
                Content = content
            };

            return responseWrapper;
        }

    }
}
